package cn.mjnxin.iot.base.util;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 环境变量路径的获取
 *
 * @author CLG 2023年10月10日
 * @version V1.0.0
 */
public class WorkFactory {
	private static Logger logger = LoggerFactory.getLogger(WorkFactory.class);

	private static String rootDir = null;

	private static String workDir;

	private static String pluginsDir;

	private static String homeDir;

	public static String getRootDirectory() {
		if (rootDir == null) {
			rootDir = initRootDirectory();
		}
		return rootDir;
	}

	private static String initRootDirectory() {
		String workpath = System.getProperty("start.root");
		if (workpath == null || "".equals(rootDir)) {
			workpath = "target";
			logger.warn("环境变量中工作目录配置不存在，使用缺省配置[-Dstart.root=" + workpath + "]！");
		} else {
			logger.info("从系统环境变量中获取工作目录为：" + workpath);
		}
		File file = new File(workpath);
		if (!file.exists()) {
			file.mkdirs();
		}
		return file.getAbsolutePath();
	}

	public static String getWorkDirectory() {
		if (workDir == null) {
			workDir = initWorkDirectory();
		}
		return workDir;
	}

	public static String getPluginsDirectory() {
		if (pluginsDir == null) {
			pluginsDir = initPluginsDirectory();
		}
		return pluginsDir;
	}

	private static String initPluginsDirectory() {
		String pluginspath = initWorkDirectory() + File.separatorChar + "plugins";
		File file = new File(pluginspath);
		if (!file.exists()) {
			file.mkdirs();
		}
		return file.getAbsolutePath();
	}

	private static String initWorkDirectory() {
		String workpath = System.getProperty("start.work");
		if (workpath == null || "".equals(workDir)) {
			workpath = "target" + File.separatorChar + "work";
			logger.warn("环境变量中工作目录配置不存在，使用缺省配置[-Dstart.work=" + workpath + "]！");
		} else {
			logger.info("从系统环境变量中获取工作目录为：" + workpath);
		}
		File file = new File(workpath);
		if (!file.exists()) {
			file.mkdirs();
		}
		return file.getAbsolutePath();
	}

	public static String getHomeDirectory() {
		if (homeDir == null) {
			homeDir = initHomeDirectory();
		}
		File file = new File(homeDir);
		if (!file.exists()) {
			file.mkdirs();
		}
		return file.getAbsolutePath();
	}

	private static String initHomeDirectory() {
		String workpath = System.getProperty("start.home");
		return getHomeDirectory(workpath);
	}

	private static String getHomeDirectory(String workpath) {
		if (workpath == null || "".equals(workDir)) {
			workpath = "target" + File.separatorChar + "home";
		} else {
			workpath = workpath.replaceAll("/", File.separator + File.separator);
		}
		while (workpath.endsWith(File.separator)) {
			workpath = workpath.substring(0, workpath.length() - 1);
		}

		File file = new File(workpath);
		if (!file.exists()) {
			file.mkdirs();
		}
		return file.getAbsolutePath();
	}

}
